<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of m_detail_pembelian
 *
 * @author fendi
 */
class m_pembelian extends Model{
    var $pembelian="pembelian";
    var $detail="detilpembelian";
    function m_pembelian(){
        parent::Model();
    }
    function getPembelianByDate($date){
        $qry=$this->db->query("SELECT
            pembelian.id_pembelian as id,
            tgl_pembelian, distributor.nama AS nama_distributor,
            sum( detail.jml_beli) as jumlah_pembelian
        FROM
            pembelian, distributor, detilpembelian AS detail
        WHERE
            tgl_pembelian ='$date' AND pembelian.id_pembelian = detail.id_pembelian AND pembelian.id_distributor=distributor.id_distributor
        GROUP BY
            pembelian.id_pembelian
        ORDER BY
            pembelian.id_pembelian desc");
        return $qry->result();
    }
    function getDetailPembelianByIdPembelian($idPembelian){
        $result=$this->db->query("select
            barang.nama_barang,
            detilpembelian.jml_beli,
            detilpembelian.harga_beli
        from detilpembelian, barang
        where detilpembelian.id_pembelian=$idPembelian AND detilpembelian.id_barang=barang.id_barang") ;
        return $result->result();
    }
    function getPembelianById($idPembelian){
        $result=$this->db->query("SELECT
            pembelian.id_pembelian as id,
            tgl_pembelian, distributor.nama AS nama_distributor
        from $this->pembelian, distributor
        WHERE id_pembelian=$idPembelian AND pembelian.id_distributor=distributor.id_distributor");
        return $result->row(0);
    }
    function insertPembelian($pembelian){
        $this->db->insert($this->pembelian,$pembelian);
    }   
    function insertDetailPembelian($detailPembelian){
        $this->db->insert($this->detail,$detailPembelian);
        //update stok barang
        $jumlahStok=$this->db->query("select jumlah_stok from barang where id_barang=".$detailPembelian['id_barang'])->row(0);
        //$this->db->set('jumlah_stok',($jumlahStok['jumlah_stok']+$detailPembelian['jml_beli']));
        $this->db->where('id_barang',$detailPembelian['id_barang']);
        $this->db->update('barang',array('jumlah_stok'=>($jumlahStok->jumlah_stok+$detailPembelian['jml_beli'])));
    }
}
?>
